package leetcode.day_2020_2021_1_18_2021_1_24;

import leetcode.Head;
import leetcode.ListNode;

/**
 * https://leetcode-cn.com/problems/add-two-numbers/
 * 2. 两数相加
 */
public class Leetcode0002 {
    public static void main(String[] args) {

    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1==null && l2==null) {
            return new ListNode(0);
        }
        ListNode head = new ListNode(-1);
        ListNode cur = head;
        int demoValue = 0;
        while (l1!=null || l2!=null) {
            // 加上进位值
            int l1_val = (l1==null) ? 0 : l1.val;
            int l2_val = (l2==null) ? 0 : l2.val;
            int num = l1_val + l2_val + demoValue;
            demoValue = num/10;
            ListNode node = new ListNode(num%10);
            cur.next = node;
            cur = cur.next;
            if(l1 != null) {
                l1 = l1.next;
            }
            if(l2 != null) {
                l2 = l2.next;
            }
        }
        // 最后判断demovalue是否为0；
        if(demoValue != 0) {
            ListNode node = new ListNode(demoValue);
            cur.next = node;
        }
        return head.next;
    }
}
